<?php
/**
 * Created by PhpStorm.
 * User: wufengjie
 * Date: 2017/8/14
 * Time: 上午11:40
 */

namespace app\need\controller;

use app\index\controller\Index;
use think\Session;

class Common// extends \think\Controller
{
    function toJson($code, $data, $msg)
    {
        $c = new M_common();
        return $c->toJson($code, $data, $msg);
    }

    function checkInput($input, $paramInfo)
    {
        $missingKeys = '';
        $emptyKeyMsg = '';
        foreach ($paramInfo as $key => $value) {
            if ($value[2] == 1) {
                $emptyRes = $this->isEmptyForKey($input, $key);
                //$emptyRes: 1没有这个key，2这个key为空，0正常
                if ($emptyRes > 1 && $emptyKeyMsg == '') {
                    $emptyKeyMsg = $value[0] . '不能为空！';
                } else if ($emptyRes == 1) {
                    $missingKeys .= $value[0] . '(' . $key . '),';
                }
            }
        }
        if ($emptyKeyMsg == '' && $missingKeys == '') {
            $msg = 'ok';
        } else {
            if ($emptyKeyMsg != '' && $missingKeys != '') {
                if (empty($input['pre'])) {
                    $msg = $emptyKeyMsg;
                } else {
                    $msg = $emptyKeyMsg . '并且缺少“' . $missingKeys . '”参数';
                }
            } else if ($missingKeys != '') {
                $msg = '缺少“' . $missingKeys . '”参数';
            } else {//if($emptyKeyMsg != '') {
                $msg = $emptyKeyMsg;
            }
        }
        return $msg;
    }

    function isEmptyForKey($param, $key)
    {
        if (isset($param[$key])) {
            $value = $param[$key];
            if (gettype($value) == 'string' && ctype_space($value)) {
                return 3;   //3表示该key的值为空格
            } else if ($value === 0 || $value == '0') {
                return 0;
            } else if (empty($value)) {
                return 2;   //2表示key为空或0
            } else {
                return 0;
            }
        } else {
            return 1;       //没有这个key
        }
    }

    /**
     * 2  * 判断字符串中是否包含指定字符串
     * 3  * @var source 源字符串
     * 4  * @var target 要判断的是否包含的字符串
     * 5  * @return bool
     * 6  */
    function isHasStr($source, $target)
    {
        preg_match_all("/" . $target . "/sim", $source, $strResult, PREG_PATTERN_ORDER);
        echo 'source==' . $source . ',,,';
        echo 'target==' . $target . ',,,';
        echo empty($strResult[0]) ? '空' : '非空';
        echo '<br>';
        return !empty($strResult[0]);
    }

    function to_json_decode($json, $isToArray = false)
    {
        $c = new M_common();
        return $c->to_json_decode($json, $isToArray);
    }


    function printR($obj, $objName = '输出对象')
    {
        $c = new M_common();
        $c->printR($obj, $objName);
    }

    function print_r($obj, $objName = '输出对象')
    {
        $c = new M_common();
        $c->print_r($obj, $objName);
    }

    function checkUnset($param, $list = [])
    {
        $c = new M_common();
        return $c->checkUnset($param, $list);
    }

    function setTitle($title)
    {
        $input = input();
        if (empty($input['pre']))
            return;

        echo '<title>' . $title . '</title>';
    }

    function apiDetail($api)
    {
        $input = input();
        if (empty($input['pre']))
            return;

        $baseUrl = 'http://' . $_SERVER['HTTP_HOST'];
        $apiUrl = $baseUrl . $_SERVER['REQUEST_URI'];
        $preUrl = $apiUrl . '/pre/1';
        Session::set('apiUrl', $preUrl);
        echo '<title>' . $api['apiName'] . '</title>';
        echo '<link href="http://api.igoyp.com/css/apilist.css" rel="stylesheet">';
        echo '接口名称：' . $api['apiName'] . '<br>';
        echo '接口地址：' . $baseUrl . '/' . $api['urlTail'] . '<br>';
        echo '<hr>';
        echo '当前完整地址：<a href="' . $apiUrl . '" target="_blank" style="text-decoration: none">' . $apiUrl . '</a><br>';
        echo '<table cellspacing = "1" bgcolor = "#bbb">';
        echo '<tr bgcolor = "#ddd">' .
            '<td align="center" width="70">参数</td>' .
            '<td align="center" width="70">描述</td>' .
            '<td align="center" width="60">类型</td>' .
            '<td align="center" width="60">必须</td>' .
            '<td align="center" width="70">示范值</td>' .
            '<td align="center" width="80">说明</td>' .
            '</tr>';

        if ($api['param'] == []) {
            echo '<tr bgcolor = "#fff">' .
                '<td>&nbsp;</td>' .
                '<td>&nbsp;</td>' .
                '<td>&nbsp;</td>' .
                '<td>&nbsp;</td>' .
                '<td>&nbsp;</td>' .
                '<td>&nbsp;</td>' .
                '</tr>';
        } else {
            foreach ($api['param'] as $key => $value) {
                if ($value[2]) {
                    $td0Css = '<td style="color: #f00">';
                    $td_css = '<td align="center" style="color: #f00">';
                    $v2 = '是';
                } else {
                    $td0Css = '<td>';
                    $td_css = '<td align="center">';
                    $v2 = '否';
                }
                $v3 = empty($value[3]) ? '' : $value[3];
                $v4 = empty($value[4]) ? '' : $value[4];
                echo '<tr bgcolor = "#fff" class="params_tr">' .
                    $td0Css . $key . '</td>' .
                    $td_css . $value[0] . '</td>' .
                    $td_css . $value[1] . '</td>' .
                    $td_css . $v2 . '</td>' .
                    $td_css . $v3 . '</td>' .
                    $td_css . $v4 . '</td>' .
                    '</tr>';
            }
        }
        echo '</table>';
        echo '<hr>';
        echo '接口返回：<br>';
    }

    function ArrayToTableHtml($api_list)
    {
        $count = count($api_list);
        $html = '<table width = "250">';// bgcolor = "#f60" cellspacing = "1"> ';
        for ($i = 0; $i < $count; $i++) {
            $obj = $api_list[$i];
            $html .= '<tr>' .            // bgcolor = "#fff" > ' .
                '<td width = "20" align = "center" > ' . $i . '</td > ' .
                '<td class="apiName" >&nbsp;' . $this->linkThis($obj) . ' </td > ' .
                '</tr > ';
        }
        $html .= '</table > ';
        return $html;
    }

    function linkThis($obj)
    {
        $index = new Index();
        $addUrl = '/';
        if ($_SERVER['HTTP_HOST'] != $index->domain_name) {
            $addUrl .= $index->domain_name . '/public/';
        }
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $addUrl . $obj['urlTail'] . '/pre/1';

        if (!empty($obj['param'])) {
            $param = $obj['param'];
            foreach ($param as $key => $value) {
//                $this->printR($value,'value');
                if (!empty($value[3]) || $value[3] == 0 || $value[3] == '0') {
                    $url .= '/' . $key . '/' . $value[3];
                }
            }
        }
        return '<a href="' . $url . '" target="iframe" >' . $obj['apiName'] . '</a>';
    }

    function getOUid($GET)
    {
//        $api = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $api = 'https://api.weixin.qq.com/sns/jscode2session';
        $api_url = $api . '?appid=' . $GET['appid'] . '&secret=' . $GET['secret'] . '&js_code=' . $GET['code'] . '&grant_type=authorization_code';
        return file_get_contents($api_url);
//        return json_decode($res);
    }

    /* 缩略图相关常量定义 */
    //常量，标识缩略图等比例缩放类型   const THUMB_SCALING   = 1;
    //常量，标识缩略图缩放后填充类型   const THUMB_FILLED    = 2;
    //常量，标识缩略图居中裁剪类型     const THUMB_CENTER    = 3;
    //常量，标识缩略图左上角裁剪类型   const THUMB_NORTHWEST = 4;
    //常量，标识缩略图右下角裁剪类型   const THUMB_SOUTHEAST = 5;
    //常量，标识缩略图固定尺寸缩放类型 const THUMB_FIXED     = 6;
    //src要服务器上的绝对路径，reCreate是否重新生成
    function make_thumb($src = '', $W = 220, $H = 220, $type = 3, $ext = 'png', $quality = 8, $reCreate = false)
    {
        $c = new M_common();
        return $c->make_thumb($src, $W, $H, $type, $ext, $quality);
    }

    //src要服务器上的绝对路径，reCreate是否重新生成
    function make220and160thumb($src = '', $type = 3, $ext = 'png', $quality = 8, $reCreate = false)
    {
        $c = new M_common();
        return $c->make220and160thumb($src, $type, $ext, $quality);
    }

    function curl_post($url, $postdata)
    {
        $postdata = json_encode($postdata);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $res = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($res, true);
        return $data;
    }

    function curl_post2($url, $param)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
//        curl_setopt($curl, CURLOPT_HEADER, 1);//作接口时，不要输出这个
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //传递post的参数变量
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        //执行命令
        $result = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return $result;
    }

    function http_post($url, $param)
    {
        $jsonStr = json_encode($param, JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return array($httpCode, $response);
    }

    function http_post_json($url, $param)
    {
        $jsonStr = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return array($httpCode, $response);
    }


    function mp_http_post($url, $param)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $this->curl_redir_exec($ch);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $return = json_decode(curl_exec($ch), true);

        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        if (isset($return['errcode']) && empty($return["errcode"])) {
            return true;
        }
        return false;
//        curl_close($ch);
    }

    function curl_redir_exec($ch)
    {
        static $curl_loops = 0;
        static $curl_max_loops = 20;
        if ($curl_loops++ >= $curl_max_loops) {
            $curl_loops = 0;
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $ret = explode("\n\n", $data, 2);
        $header = $ret[0];
        if (isset($ret[1])) $data = $ret[1];

        //        list($header, $data) = explode("\n\n", $data, 2);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302) {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = @parse_url(trim(array_pop($matches)));
            if (!$url) {
                //couldn't process the url to redirect to
                $curl_loops = 0;
                return $data;
            }
            $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!$url['scheme'])
                $url['scheme'] = $last_url['scheme'];
            if (!$url['host'])
                $url['host'] = $last_url['host'];
            if (!$url['path'])
                $url['path'] = $last_url['path'];
            $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query'] ? '?' . $url['query'] : '');
            curl_setopt($ch, CURLOPT_URL, $new_url);
            debug('Redirecting to', $new_url);
            return $this->curl_redir_exec($ch);
        } else {
            $curl_loops = 0;
            return $data;
        }
    }
}